package com.woniuxy.reader.service.impl;

import com.woniuxy.reader.entity.*;
import com.woniuxy.reader.mapper.*;
import com.woniuxy.reader.service.SubscribeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.reader.vo.SubscribeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zh_o
 * @since 2020-10-12
 */
@Service
public class SubscribeServiceImpl extends ServiceImpl<SubscribeMapper, Subscribe> implements SubscribeService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private SubscribeMapper subscribeMapper;

    @Resource
    private BookDataMapper bookDataMapper;

    @Resource
    private ChapterMapper chapterMapper;

    @Resource
    private BookMapper bookMapper;

    /**
     * 新增订阅
     * @param subscribe
     */
    @Override
    public void insertSubscribe(Subscribe subscribe) {
        // 获取章节信息
        Chapter chapter = chapterMapper.selectById(subscribe.getChapterId());
        // 判断用户余额是否足够
        User user = userMapper.selectById(subscribe.getUserId());
        if (user.getBalance() < chapter.getAmount()) {
            throw new RuntimeException("余额不足");
        }
        // 新增订阅
        subscribeMapper.insert(subscribe);
        // 修改用户余额
        double amount = (double) chapter.getAmount();
        user.setBalance(user.getBalance() - (int)amount);
        userMapper.updateById(user);
        // 获取书籍信息
        Book book = bookMapper.selectById(chapter.getBookId());
        // 根据书籍id 获取书籍数据
        BookData bookData = bookDataMapper.selectById(book.getBookId());
        // 订阅量加一
        bookData.setSubscribe(bookData.getSubscribe() + 1);
        bookDataMapper.updateById(bookData);
    }

    @Override
    public List<SubscribeVO> selectSubscribeByUserId(String userid) {

        return subscribeMapper.selectSubscribeByUserId(userid);
    }
}
